<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
	class Manage_card extends CI_Controller{
		var      $mark, $card_no;	
		public function __construct(){
			parent::__construct();
			$this->load->library('session');
			$this->load->library('form_validation');
			$this->load->library('cismarty');
			$this->load->model("apanel/template");
			$this->load->model("apanel/db_card");
			$this->load->model("apanel/db_customer");
			$this->load->library('pagination');
			$mark  = 3;
		}
		
		public function index(){
			//== template
			redirect('manage_card/card_list');
		}
		
		public function card_list($st=""){
			if($this->session->userdata('sess_login') == null)
				redirect('apanel');
			list($item,$num,$page,$total) = $this->listall();
			$this->cismarty->assign("total",$total);
			if($st == "success"){
				$this->cismarty->assign("status","<div class=\"mws-form-message success message\">Success</div>");
			}
			$scripts = '
			<script type="text/javascript" charset="utf-8">
			$(document).ready(function() {
			$(\'#table1\').dataTable( {
			"bJQueryUI": true,
			"bProcessing": true,
			"bServerSide": true,
			"sAjaxSource": "'.base_url().'manage_card/datalist",
			"iDisplayStart"  : 0,
			"sPaginationType": "full_numbers",
			"aaSorting": [[ 0, "desc" ]],
			"aoColumnDefs": [
			{ "bSortable": false, "aTargets": [ 0 ] },
			],
			"fnServerData": function(sSource, aoData, fnCallback)
			{
			$.ajax(
			{
			\'dataType\': \'json\',
			\'type\'  : \'POST\',
			\'url\'    : sSource,
			\'data\'  : aoData,
			\'success\' : fnCallback
			}
			);
			}
			} );
			} );
			</script>';
			$this->cismarty->assign("scripts",$scripts);
			//== template
			$this->cismarty->assign("header",$this->template->header());
			$this->cismarty->assign("menu",$this->template->menu(5));
			$this->cismarty->assign("footer",$this->template->footer());
			$this->cismarty->assign("url",base_url());
			$this->cismarty->assign("form_open",form_open('manage_card/card_delAll'));
			$this->cismarty->assign("form_close",form_close());
			$this->cismarty->display('apanel/card/card_list.html');
		}
		
		public function datalist(){
			$output = $this->db_card->datalist();
			echo json_encode($output);
		}
		
		public function listall(){
			$config['base_url'] = base_url().'manage_card/card_list';
			$config['total_rows'] = $this->db->count_all("mobile_card");
			$config['per_page'] = 20;
			$config['full_tag_open'] = '<div class="pages">';
			$config['full_tag_close'] = '<div>';
			$this->pagination->initialize($config);
			$this->db->limit($config['per_page'],$this->uri->segment(3));
			$this->db->select("t1.pkid,t1.card_no,t2.name");
			$this->db->from("mobile_card t1");
			$this->db->join("mobile_customer t2", "t1.customer_pkid = t2.pkid");
			$this->db->limit($config['per_page'],$this->uri->segment(4));
			$this->db->order_by("t1.pkid", "desc");
			$res = $this->db->get();
			//==
			$no = $this->uri->segment(3)+1;
			$i = 1;
			$arr = $res->result_array();
			$item = array();
			foreach ($arr as $P){
				if($i %2 == 0)
					$tmp['back']							="#FFFFFF";
				else
					$tmp['back']							="#F4F4F4";
				$i++;
				$tmp['no']							=$no;
				$tmp['pkid']						=$P['pkid'];
				$tmp['card_no']						=$P['card_no'];
				$tmp['customer']					=$P['name'];
				$item[] = $tmp;
				$no = $no+1;
			}
			$num_row = $config['total_rows'];
			$pagelink  = $this->pagination->create_links();
			return array($item,$num_row,$pagelink,$config['total_rows']);
		}

		public function card_add(){
			if($this->session->userdata('sess_login') == null)
				redirect('apanel');			
			if($this->input->post('bntSubmit') != null){
				$this->form_validation->set_rules("country","Country","required");
				$this->form_validation->set_rules("customer","Customer","required");
				$this->form_validation->set_rules("package","Package","required");
				$this->form_validation->set_rules("card_from","Card From","required");
				$this->form_validation->set_rules("card_to","Card To","required");

				if($this->form_validation->run() == FALSE){
					$this->cismarty->assign("country",set_value('country'));
					$this->cismarty->assign("customer",set_value('customer'));
					$this->cismarty->assign("package",set_value('package'));
					$this->cismarty->assign("card_from",set_value('card_from'));
					$this->cismarty->assign("card_to",set_value('card_to'));
						
					//set error
					$this->cismarty->assign("country",form_error('country'));
					$this->cismarty->assign("customer",form_error('customer'));
					$this->cismarty->assign("package",form_error('package'));
					$this->cismarty->assign("card_from",form_error('card_from'));
					$this->cismarty->assign("card_to",form_error('card_to'));

				}else {


					for ($i=$this->input->post('card_from');$i<=$this->input->post('card_to');$i++){
//						$card_no = trim($this->input->post('country')).str_pad(trim($this->input->post('customer')), 4, "0", STR_PAD_LEFT).str_pad($i, 8, "0", STR_PAD_LEFT);

						$card_no = str_pad($i, 6, "0", STR_PAD_LEFT);

						$data = array(
								"customer_pkid"=>trim($this->input->post('customer')),
								"status"=>1,
								"password"=>$this->makePin(),
								"card_no"=>$card_no,
								"status"=>1,
								"current_package"=>trim($this->input->post('package')),
								"created_date"=>date("Y-m-d H:i:s"),
						);
						$res = $this->db->insert("mobile_card",$data);
					}

					if($res) redirect('manage_card/card_list/success');
					else  redirect('manage_card/card_list/fail');
				}
		
			}
			$this->cismarty->assign("tiny",$this->template->tinymce());
			$this->cismarty->assign("customer",$this->show_customer());
			$this->cismarty->assign("country",$this->show_country());
			$this->cismarty->assign("package",$this->show_package());
			//== template
			$this->cismarty->assign("header",$this->template->header());
			$this->cismarty->assign("menu",$this->template->menu(5,2));
			$this->cismarty->assign("footer",$this->template->footer());
			$this->cismarty->assign("url",base_url());
			$this->cismarty->assign("form_open",form_open_multipart("manage_card/card_add"));
			$this->cismarty->assign("form_close",form_close());
			$this->cismarty->display('apanel/card/card_add.html');
		}
		
		public function card_edit($id){

			if($this->input->post('bntSubmit') != null){
				$this->form_validation->set_rules("customer","Customer","required");
				$this->form_validation->set_rules("package","Package","required");
				$this->form_validation->set_rules("card_no","Card No.","required");


				if($this->form_validation->run() == FALSE){
					$this->cismarty->assign("customer",set_value('customer'));
					$this->cismarty->assign("package",set_value('package'));
					$this->cismarty->assign("card_no",set_value('card_no'));

			
					//set error
					$this->cismarty->assign("customer",form_error('customer'));
					$this->cismarty->assign("package",form_error('package'));
					$this->cismarty->assign("card_no",form_error('card_no'));
				}else {
						$data = array(
								"customer_pkid"=>$this->input->post('customer'),
								"current_package"=>trim($this->input->post('package')),
								"card_no"=>trim($this->input->post('card_no'))

						);
						$this->db->where("pkid",$id);
						$res = $this->db->update('mobile_card',$data);
						if($res) redirect('manage_card/card_list/success');
						else  redirect('manage_card/card_list/fail');

				}

			}else {
				$this->db->where("pkid",$id);
				$res = $this->db->get('mobile_card');
				$row = $res->row();
				$this->cismarty->assign("card_no",$row->card_no);
				$this->cismarty->assign("password",$row->password);
				$customer_pkid 	= $row->customer_pkid;
				if($row->status == 1) $this->cismarty->assign("sa",'checked="checked"');
				else $this->cismarty->assign("sd",'checked="checked"');

 			}
			$this->cismarty->assign("tiny",$this->template->tinymce());
			$this->cismarty->assign("customer",$this->show_customer($customer_pkid));
			$this->cismarty->assign("package",$this->show_package($row->current_package));

			//== template
			$this->cismarty->assign("header",$this->template->header());
			$this->cismarty->assign("menu",$this->template->menu(5,2));
			$this->cismarty->assign("footer",$this->template->footer());
			$this->cismarty->assign("url",base_url());
			$this->cismarty->assign("form_open",form_open_multipart("manage_card/card_edit/$id"));
			$this->cismarty->assign("form_close",form_close());
			$this->cismarty->display('apanel/card/card_edit.html');
		}

		public function del($id){
		
		}

		private function makePin($lenth =6) {
			// makes a random alpha numeric string of a given lenth
			$aZ09 = array_merge(range('A', 'H'), range('J', 'N'), range('P', 'Z'), range(2, 9));
			$out ='';
			for($c=0;$c < $lenth;$c++) {
			   $out .= $aZ09[mt_rand(0,count($aZ09)-1)];
			}
			return $out;
		}

		public function show_customer($group = ""){
			$this->db->order_by("pkid","desc");
			$res = $this->db->get('mobile_customer');
			$str = '<option value="0">Select Customer</option>';
			foreach ($res->result_array() as $P){
				if($group == $P['pkid']){
					$check = "selected";
				}else{
					$check = "";
				}
				$str .='<option value="'.$P['pkid'].'" '.$check.'>'.$P['name'].'</option>';
			}
			return $str;
		}

		public function show_country($group = ""){
		//	if($group != "")
			if($this->session->userdata("sess_customer_name") != "eshine")
				$this->db->where("pkid",$this->session->userdata("sess_customer_id"));
			$this->db->order_by("code");
			$res = $this->db->get('mobile_country');
			$str = '<option value="0">Select Country</option>';
			foreach ($res->result_array() as $P){
				if($group == $P['pkid']){
					$check = 'selected="selected"';
				}else{
					$check = "";
				}
				$str .='<option value="'.$P['code'].'" '.$check.'>'.$P['code']." | ".$P['name'].'</option>';
			}
			return $str;
		}

		public function show_package($package = ""){

			$str = '<option value="0">Select Package</option>';

				$str .='<option value="12" '; if($package == 12){ $str .= 'selected';} $str .='>12 Months</option>';
				$str .='<option value="24" '; if($package == 24){ $str .= 'selected';} $str .='>24 Months</option>';
				$str .='<option value="60" '; if($package == 60){ $str .= 'selected';} $str .='>60 Months</option>';

			return $str;
		}
	}
?>